package cn.gyx.hrm.mq.consumer;

import cn.gyx.hrm.to.EmailTo;
import cn.gyx.hrm.to.SMSTo;
import cn.gyx.hrm.to.SystemTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.util.List;

import static cn.gyx.hrm.constants.RabbitMQConstants.*;

@Component
@Slf4j
public class MessageConsumer {
    @RabbitListener(queues = QUEUE_NAME_SMS ,containerFactory = "rabbitListenerContainerFactory")
    public void consumerSMS(@Payload SMSTo smsTo, Channel channel, Message message){
        // 获取手机号
        List<String> phones = smsTo.getPhones();
        //发送短信
        String join = StringUtils.join(phones, ",");
        log.info(join,smsTo.getContent(),message);
        //todo
        //手动签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RabbitListener(queues = QUEUE_NAME_EMAIL ,containerFactory = "rabbitListenerContainerFactory")
    public void consumerEmail(@Payload EmailTo emailTo, Channel channel, Message message){
        // 获取邮箱
       emailTo.getEmials().forEach(email->{
           // 发送邮件
           log.info(email,emailTo.getTitle(),emailTo.getContent());

       });
        //手动签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RabbitListener(queues = QUEUE_NAME_SYSTEM_MESSAGE ,containerFactory = "rabbitListenerContainerFactory")
    public void consumerSystem (@Payload SystemTo systemTo,Channel channel,Message message){
       // 得到并保存站内信息
        systemTo.getIds().forEach(userid->{
            log.info(String.valueOf(userid),systemTo.getTitle(),systemTo.getContent());
        });
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
